import { View, Image, Text, CoverImage, RichText } from '@tarojs/components'
import { useState, useEffect, useRef } from 'react'
import LgButton from '@/pages/components/button'
import LgInput from '@/pages/components/input'
import LgCell from '@/pages/components/cell'
import { LgPopLayer } from '@/pages/components/popLayer'
import LgSwitch from '@/pages/components/switch'
import Header from '@/pages/components/navCustomBar'
import { LgCalendar } from '@/pages/components/calendar'
import LgTimeSelect from '@/pages/components/timeSelectOld';
import LgCheckbox from '@/pages/components/checkbox'
import { LgSlide } from '@/pages/components/slides'
import LgSeleTarget from '@/pages/components/seleTarget'
import LgSelectModal from '@/pages/components/LgSelectModal'
import Taro from '@tarojs/taro'
import Proxy from '@/network/proxy'
import { requestSystemUrl } from '@/network/baseUrl'
import dayjs from 'dayjs'
import { HttpGet, HttpPut, HttpPost, getData, HttpDelete } from '@/network/servers'
import Utils from '@/utils/index'
import { connect, useDispatch, useSelector } from 'react-redux'
import { setSelectUser } from '@/store/slice'
import { getBrowserController, getNet, getStorage, getWxSDKParams } from '@/pages/components/utils';
import '../../images/public/style.css'
import './index.scss'
import PrPopInput from '../popInput'
import { DatePicker, } from '@nutui/nutui-react-taro'

import { isBuffer, values } from 'lodash'
import Item from 'antd-mobile/es/components/dropdown/item'
const browserController = getBrowserController()
const net = getNet()
const storage = getStorage()

var wx = require('weixin-js-sdk')
const {
  getQueryVariable,
  constructionDate2,
  getDate
} = Utils

function App(props) {
  const dispatch = useDispatch()
  let arr33 = useSelector((state: any) => state.commonData.selectUserList) // 获取redux中的参与人
  console.log(arr33)
  let {
    userInfo,
    baseUrl,
    selectUserList
  } = props
  
  const getToken = () => {
    if (getQueryVariable('env') === 'weapp') {
      return getQueryVariable('lg_tk')
    } else {
      return storage.get('token') || getQueryVariable('lg_tk')
    }
  }

  const [init, setInit] = useState(true);
  const [scheduleId, setScheduleId] = useState('')//日程ID
  const [title, setTitle] = useState('')//日程标题
  const [address, setAddress] = useState('')//日程地点
  const [description, setDescription] = useState('')//日程描述
  const [currentTime, setCurrentTime] = useState(dayjs().add(0.5, 'h').format('HH:mm:ss'))//当前时间
  const [currentTimeEnd, setCurrentTimeEnd] = useState(dayjs().add(1.5, 'h').format('HH:mm:ss'))//当前时间(结束时间)
  const [regularList, setRegularList] = useState([])
  const [visible, setVisible] = useState(false)
  const [reminderName, setReminderName] = useState('')//日程提醒选择
  const [reminderTime, setReminderTime] = useState(0)//日程提醒时间
  const [remindFlag, setRemindFlag] = useState(0)//是否提醒
  const [isAllDay, setIsAllDay] = useState(0) //全天
  const [isRepeat, setIsRepeat] = useState(false) //日程重复
  const [isSkip, setIsSkip] = useState(false) //跳过节假日
  const [repeatTime, setRepeatTime] = useState(0) //日程重复时间标识 
  const [repeatTimeList, setRepeatTimeList] = useState([]) //重复时间列表
  const [repeatEndTime, setRepeatEndTime] = useState('') //重复结束日期
  const [repeatEndShow, setRepeatEndShow] = useState(false) //重复结束日期
  const [beSkipHolidays, setBeSkipHolidays] = useState(1) //是否跳过节假日
  const [inviteCount, setInviteCount] = useState(0) //会议邀请人数
  const [termStartDate, setTermStartDate] = useState("2023-03-01") //学期开始日期
  const [termEndDate, setTermEndDate] = useState("2023-07-02") //学期结束日期
  const [startShow, setStartShow] = useState(false) //开始日期选择
  const [endShow, setEndShow] = useState(false)//结束日期选择
  const [visibleStart, setVisibleStart] = useState(false)//开始时间选择
  const [visibleEnd, setVisibleEnd] = useState(false)//结束时间选择
  const [startDate, setStartDate] = useState(dayjs().format('YYYY-MM-DD'))//开始日期
  const [endDate, setEndDate] = useState(dayjs().format('YYYY-MM-DD'))//结束日期
  const [startTime, setStartTime] = useState(dayjs().add(1, 'hour').startOf('hour').format('HH:mm'))//开始时间 时分
  const [endTime, setEndTime] = useState(dayjs().add(2, 'hour').startOf('hour').format('HH:mm'))//结束时间 时分
  const [startTimeAll, setStartTimeAll] = useState(dayjs().add(1, 'hour').startOf('hour').format('YYYY-MM-DD HH:mm'))//开始时间  (YYYY-MM-DD HH:mm)
  const [endTimeAll, setEndTimeAll] = useState(dayjs().add(2, 'hour').startOf('hour').format('YYYY-MM-DD HH:mm'))//结束时间 (YYYY-MM-DD HH:mm)
  const [frequencyShow, setFrequencyShow] = useState(false) //提醒频率弹窗
  const [isSelect, setIsSelect] = useState(false) //提醒日期选中状态
  const [isCheck, setIsCheck] = useState(0) //提醒日期复选框
  const [oldPeopleList, setOldPeopleList] = useState([]) //旧参与人列表
  const [oldScheduleTime, setOldScheduleTime] = useState('') //旧日程日期
  const [mainScheduleId, setMainScheduleId] = useState('') //重复日程主日程ID
  const [externalScheduleId, setExternalScheduleId] = useState('') //对外创建的日程ID
  const [beExternal, setBeExternal] = useState(0) //是否外部对接1是，0否（默认）
  const [notDetail, setNotDetail] = useState(false) //2023-05-11 修复点击编辑提示日程不存在
  const [commonlyVisible, setCommonlyVisible] = useState(false) //2023-09-26 增加常用日程修改
  const [inputPopOpen, setInputPopOpen] = useState(false)//2023-10-08 增加常用日程修改名称
  const [inputPopOpenNew, setInputPopOpenNew] = useState(false)//2023-10-09 新增常用日程
  const [oldValue, setOldValue] = useState('')//2023-10-08 常用日程旧名称
  const [oldItem, setOldItem] = useState('')//2023-10-08 保存所修改的某条常用日程
  const [beSign, setBeSign] = useState(false);
  const [reminderList, setReminderList] = useState([
    {
      "id": "1",
      "reminderName": "不提醒",
      "reminderTime": '',
    },
    {
      "id": "2",
      "reminderName": "开始时",
      "reminderTime": 0,
    },
    {
      "id": "3",
      "reminderName": "开始前5分",
      "reminderTime": 5,
    },
    {
      "id": "4",
      "reminderName": "开始前15分",
      "reminderTime": 15,
    },
    {
      "id": "5",
      "reminderName": "开始前30分",
      "reminderTime": 30,
    },
    {
      "id": "6",
      "reminderName": "开始前1小时",
      "reminderTime": 60,
    },
    {
      "id": "7",
      "reminderName": "开始前2小时",
      "reminderTime": 120,
    },
  ])//日程提醒
  const repeatTimeTypeList = [{
    id: 1,
    repeatName: '按日'
  },
  {
    id: 2,
    repeatName: '按周'
  },
  {
    id: 3,
    repeatName: '按月'
  }]
  const repeatTimeType = {
    '0': '不重复',
    '1': '按日',
    '2': '按周',
    '3': '按月',
  }
  const week = [
    {
      id: '1',
      weekName: '一'
    },
    {
      id: '2',
      weekName: '二'
    },
    {
      id: '3',
      weekName: '三'
    },
    {
      id: '4',
      weekName: '四'
    },
    {
      id: '5',
      weekName: '五'
    },
    {
      id: '6',
      weekName: '六'
    },
    {
      id: '7',
      weekName: '日'
    },
  ]

  // 2024-06-20引入新版组件库导致无法正常选择日期时间，更换为nut ui
  const startDate1 = dayjs().toDate();
  const endDate1 = dayjs().add(1, 'year').toDate();
  const saveTimeNew = (values: (string | number)[], options: PickerOption[], type) => {
    const date = values.slice(0, 3).join('-')
    const time = values.slice(3).join(':')
    let newTime = dayjs(`${date} ${time}`).format('YYYY-MM-DD HH:mm')
    if (type === 'start') {
      setStartTimeAll(newTime)
      setEndTimeAll(dayjs(newTime).add(1, 'hour').startOf('hour').format('YYYY-MM-DD HH:mm'))
    } else if (type === 'end') {
      setEndTimeAll(newTime)
    } else {
      setRepeatEndTime(dayjs(newTime).format('YYYY-MM-DD'));
    }
  }
  //快速生成一个月
  const month = new Array();
  for (let i = 1; i <= 31; i++) {
    month.push({ id: `${i}` })
  }

  //初始化所有数据
  const initData = () => {
    console.log('初始化');
    // setInit(false);
    setScheduleId('');
    setAddress('');
    setDescription('');
    storage.set('toChooseObject', JSON.stringify([]))
    dispatch({ type: 'SET_SELECTUSERLIST', data: [] })
    setTitle('');
    // if (selectUserList && selectUserList.length > 0) {
    //   dispatch({ type: 'SET_SELECTUSERLIST', data: setSelectUser([]) });//参与人
    // }
  }

  const getCommonData = () => {
    setInit(false)
    if (Utils.getQueryVariable('env') === 'weapp' || window.__wxjs_environment === 'miniprogram') {
      // 小程序端的h5
      if (!baseUrl) {
        // 直接跳转当前页面

      } else {
        console.log("小程序");
        let instance = Taro.getCurrentInstance()
        const browserController = getBrowserController()
        if (instance.router?.params) {
          let params = instance.router.params
          //获取学期区间
          Taro.getSysWeb({ sysId: '000', eduId: Utils.getQueryVariable('eduId') || userInfo.eduId }, 'web', function (res) {
            let MainServerAddr = res
            HttpGet({   //基础平台地址
              // url: MainServerAddr + '/ScheduleExternal/api/university/getTermInfo',
              url: '/api/common/school/term/current/info',
              data: {
                eduId: Utils.getQueryVariable('eduId') || userInfo.eduId
              }
            }).then((res1) => {
              if (res1.data) {
                let data = res1.data;
                setTermStartDate(dayjs(data.termStartDate).format('YYYY-MM-DD'));
                setTermEndDate(dayjs(data.termEndDate).format('YYYY-MM-DD'))
              }
            })
          })
          let signin = params?.signin || 0
          let date = params?.date
          let startDate = params.startDate
          let startTime = params.start
          let endTime = params.end
          if(signin ==1){
            setInit(true);
            initData();
            setStartDate(dayjs(date).format('YYYY-MM-DD'));
            setEndDate(dayjs(date).format('YYYY-MM-DD'));
            setStartTimeAll(dayjs(date + ' ' + dayjs().add(1, 'hour').startOf('hour').format('HH:mm')).format('YYYY-MM-DD HH:mm'));
            setEndTimeAll(dayjs(date + ' ' + dayjs().add(2, 'hour').startOf('hour').format('HH:mm')).format('YYYY-MM-DD HH:mm'));
            return;
          }
          if (startDate) {
            setInit(true);
            initData();
            setStartDate(dayjs(startDate).format('YYYY-MM-DD'));
            setEndDate(dayjs(startDate).format('YYYY-MM-DD'));
            setStartTime(startTime);
            setEndTime(endTime);
            setStartTimeAll(dayjs(startDate + ' ' + startTime).format('YYYY-MM-DD HH:mm'));
            setEndTimeAll(dayjs(startDate + ' ' + endTime).format('YYYY-MM-DD HH:mm'));
            return;
          }
          let id = params.id;
          if (!id || notDetail) {
            setInit(true);
            initData();
            return;
          }
          setScheduleId(id);
          let url = "/api/schedule/info/detail";
          HttpGet({
            url,
            data: {
              scheduleId: id,
              userId: userInfo.userId,
              eduId: userInfo.eduId,
              userType: userInfo.userType,
            }
          }).then(res => {
            if (res.code == 200 && res.data) {
              let data = res.data
              setTitle(data.scheduleTitle);
              setStartDate(data.scheduleDate);
              setEndDate(data.scheduleDate);
              setStartTime(data.startTime);
              setEndTime(data.endTime);
              setStartTimeAll(dayjs(data.scheduleDate + ' ' + data.startTime).format('YYYY-MM-DD HH:mm'));
              setEndTimeAll(dayjs(data.scheduleDate + ' ' + data.endTime).format('YYYY-MM-DD HH:mm'));
              if (data.beAllDay === '1') {
                // console.log(data, 'datadatadat1111a', data.beAllDay);
                setIsAllDay(1);
              } else {
                setIsAllDay(0);
              }
              setBeSign(data?.beSignIn == '1' ? true : false);
              setAddress(data.scheduleLocation);
              setDescription(data.scheduleContent);
              setRemindFlag(data.remindFlag);
              if (data.repeatTime == '0') {
                setIsRepeat(false);
              } else {
                setIsRepeat(true);
              }
              if (data.beSkipHolidays == '0') {
                setIsSkip(false);
              } else {
                setIsSkip(true);
              }
              if (data.remindFlag == '1') {
                switch (data.remindTime) {
                  case '0': setReminderName('开始时');
                    break;
                  case '5': setReminderName('开始前5分');
                    break;
                  case '15': setReminderName('开始前15分');
                    break;
                  case '30': setReminderName('开始前30分');
                    break;
                  case '60': setReminderName('开始前1小时');
                    break;
                  case '120': setReminderName('开始前2小时');
                    break;
                }
              } else {
                setReminderName('不提醒');
              }
              setReminderTime(data.remindTime);
              setRepeatTime(data.repeatTime);
              dispatch({ type: 'SET_SELECTUSERLIST', data: setSelectUser(data?.scheduleMemberVoList ? data?.scheduleMemberVoList :[]) });//参与人
              if (data.repeatEndTime) {
                setRepeatEndTime(dayjs(data.repeatEndTime.slice(0, 10)).format('YYYY-MM-DD'));
              }
              setRepeatTimeList(data.repeatTimeList);
              setOldPeopleList(data.scheduleMemberVoList);
              setOldScheduleTime(data.scheduleDate);
              dispatch({ type: 'SET_SELECTUSERLIST', data: data.scheduleMemberVoList })
              storage.set('toChooseObject', JSON.stringify(data.scheduleMemberVoList))
              arr33 = data.scheduleMemberVoList
              setMainScheduleId(data.mainScheduleId);
              if (data.beExternal || data.externalScheduleId) {
                setExternalScheduleId(data.externalScheduleId);
                setBeExternal(data.beExternal);
              }
              setInit(true);
            } else {
              Taro.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          })

        }
      }
    } else {
      // app内 1.应用内跳转(不需要获取通知地址和用户信息) 2.直接跳转
      let instance = Taro.getCurrentInstance();
      const browserController = getBrowserController();
      if (instance.router?.params) {
        //获取学期区间
        let MainServerAddr = storage.get('baseUrl');
        HttpGet({   //基础平台地址
          // url: MainServerAddr + '/ScheduleExternal/api/university/getTermInfo',
          url: '/api/common/school/term/current/info',
          data: {
            eduId: Utils.getQueryVariable('eduId') || userInfo.eduId
          }
        }).then((res) => {
          if (res.data) {
            let data = res.data;
            setTermStartDate(dayjs(data.termStartDate).format('YYYY-MM-DD'));
            setTermEndDate(dayjs(data.termEndDate).format('YYYY-MM-DD'))
          }
        })
        let params = instance.router.params
        let signin = params?.signin || 0
        let date = params?.date
        let startDate = params.startDate
        let startTime = params.start
        let endTime = params.end
        if(signin ==1){
          setInit(true);
          initData();
          setStartDate(dayjs(date).format('YYYY-MM-DD'));
          setEndDate(dayjs(date).format('YYYY-MM-DD'));
          setStartTimeAll(dayjs(date + ' ' + dayjs().add(1, 'hour').startOf('hour').format('HH:mm')).format('YYYY-MM-DD HH:mm'));
          setEndTimeAll(dayjs(date + ' ' + dayjs().add(2, 'hour').startOf('hour').format('HH:mm')).format('YYYY-MM-DD HH:mm'));
          return;
        }
        if (startDate) {
          setInit(true);
          initData();
          setStartDate(startDate);
          setEndDate(startDate);
          setStartTime(startTime);
          setEndTime(endTime);
          setStartTimeAll(dayjs(startDate + ' ' + startTime).format('YYYY-MM-DD HH:mm'));
          setEndTimeAll(dayjs(startDate + ' ' + endTime).format('YYYY-MM-DD HH:mm'));
          return;
        }
        let id = params.id;
        if (!id || notDetail) {
          setInit(true);
          initData();
          return;
        }
        setScheduleId(id);
        let url = "/api/schedule/info/detail";
        console.log('zheli', id);

        HttpGet({
          url,
          data: {
            scheduleId: id,
            userId: userInfo.userId,
            eduId: userInfo.eduId,
            userType: userInfo.userType,
          }
        }).then(res => {
          if (res.code == 200 && res.data) {
            let data = res.data
            setTitle(data.scheduleTitle);
            setStartDate(data.scheduleDate);
            setEndDate(data.scheduleDate);
            setStartTime(data.startTime);
            setEndTime(data.endTime);
            setStartTimeAll(dayjs(data.scheduleDate + ' ' + data.startTime).format('YYYY-MM-DD HH:mm'));
            setEndTimeAll(dayjs(data.scheduleDate + ' ' + data.endTime).format('YYYY-MM-DD HH:mm'));
            if (data.beAllDay === '1') {
              // console.log(data, 'datadatadat1111a', data.beAllDay);
              setIsAllDay(1);
            } else {
              setIsAllDay(0);
            }
            if (data.beSkipHolidays == '0') {
              setIsSkip(false);
            } else {
              setIsSkip(true);
            }
            setBeSign(data?.beSignIn == '1' ? true : false);
            setAddress(data.scheduleLocation);
            setDescription(data.scheduleContent);
            setRemindFlag(data.remindFlag);
            if (data.repeatTime == '0') {
              setIsRepeat(false);
            } else {
              setIsRepeat(true);
            }
            if (data.remindFlag == '1') {
              switch (data.remindTime) {
                case '0': setReminderName('开始时');
                  break;
                case '5': setReminderName('开始前5分');
                  break;
                case '15': setReminderName('开始前15分');
                  break;
                case '30': setReminderName('开始前30分');
                  break;
                case '60': setReminderName('开始前1小时');
                  break;
                case '120': setReminderName('开始前2小时');
                  break;
              }
            } else {
              setReminderName('不提醒');
            }
            setReminderTime(data.remindTime);
            setRepeatTime(data.repeatTime);
            dispatch({ type: 'SET_SELECTUSERLIST', data: setSelectUser(data?.scheduleMemberVoList ? data?.scheduleMemberVoList :[]) });//参与人
            if (data.repeatEndTime) {
              setRepeatEndTime(dayjs(data.repeatEndTime.slice(0, 10)).format('YYYY-MM-DD'));
            }
            setRepeatTimeList(data.repeatTimeList);
            setOldPeopleList(data.scheduleMemberVoList);
            setOldScheduleTime(data.scheduleDate);
            dispatch({ type: 'SET_SELECTUSERLIST', data: data.scheduleMemberVoList })
            storage.set('toChooseObject', JSON.stringify(data.scheduleMemberVoList))
            arr33 = data.scheduleMemberVoList
            setMainScheduleId(data.mainScheduleId);
            if (data.beExternal || data.externalScheduleId) {
              setExternalScheduleId(data.externalScheduleId);
              setBeExternal(data.beExternal);
            }
            setInit(true);
          } else {
            Taro.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        })

      }
    }
  }

  //获取全部类型
  const getRegularList = () => {
    let url = '/api/schedule/regular/list'
    HttpGet({
      url,
      data: {
        userId: userInfo.userId,
        eduId: userInfo.eduId,
        userType: userInfo.userType,
      }
    }).then((res) => {
      if (res.code == 200) {
        let data = res.data;
        data.forEach(item => {
          if (item.beInit == 0) { // 初始常用日程
            item.optionList = [
              { text: '编辑', onClick: () => operation('set', item), className: 'edit' },
              { text: '删除', onClick: () => operation('del', item), className: 'delete' }]
          } else {
            item.optionList = [
              { text: '删除', onClick: () => operation('del', item), className: 'delete' },
            ]
          }
        });
        setRegularList(data)
      }
    })
  }

  //打开弹窗
  const handlePopLayer = (type, flag) => {
    if (beExternal == 1 && flag !== 'reminder') {
      Taro.showToast({
        title: '对外日程仅可修改提醒时间！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (type === 'open') {
      //打开弹出层时阻止页面滑动
      document.body.style.overflow = 'hidden';

      // document.body.addEventListener("touchmove", bodyScroll, { passive: false });
      switch (flag) {
        case 'start': setStartShow(true);
          break;
        case 'end': setEndShow(true);
          break;
        case 'repeatEnd': setRepeatEndShow(true);
          break;
        case 'frequency': setFrequencyShow(true);
          break;
        default: setVisible(true);
          break;
      }

    } else {
      document.body.style.overflow = '';

      switch (flag) {
        case 'start': setStartShow(false);
          break;
        case 'end': setEndShow(false);
          break;
        case 'repeatEnd': setRepeatEndShow(false);
          break;
        case 'frequency': setFrequencyShow(false), setRepeatTimeList([]);
          break;
        case 'commonly': setCommonlyVisible(false);
          break;
        default: setVisible(false);
          break;
      }

    }
  }
  //选择提醒时间
  const changeScheduleTime = (obj) => {
    setReminderName(obj.reminderName);
    setReminderTime(obj.reminderTime);
    handlePopLayer('close', 'reminder');
  }

  //发布/编辑日程
  const createSchedule = () => {
    if (title.length == 0) {
      Taro.showToast({
        title: '日程标题不能为空！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (startTimeAll == '') {
      Taro.showToast({
        title: '请选择开始时间！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (endTimeAll == '') {
      Taro.showToast({
        title: '请选择结束时间！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (startTimeAll >= endTimeAll) {
      Taro.showToast({
        title: '结束时间应大于开始时间！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (isRepeat == true) {
      if (repeatEndTime == '') {
        Taro.showToast({
          title: '请选择结束重复时间！',
          icon: 'none',
          duration: 2000
        })
        return
      }
    }

    Taro.showToast({
      title: '正在保存~',
      icon: 'none'
    })
    let url = ''
    if (scheduleId == '') {
      url = '/api/schedule/created/save';
    } else {
      url = '/api/schedule/created/update';
      setNotDetail(true);
    }
    //计算提醒时间
    let time = startTimeAll;
    let times = dayjs(time).subtract(120, 'm')?.$d;
    let remindRealTime = '';
    if (isAllDay == 1) {
      remindRealTime = dayjs(startTimeAll).format('YYYY-MM-DD HH:mm:ss');
    } else {
      remindRealTime = dayjs(times).format('YYYY-MM-DD HH:mm:ss');
    }
    let numberList: any[] = []
    if (arr33.length > 0) {
      arr33.forEach(i => {
        if (i.hasOwnProperty('structureVoList')) {
          i.structureVoList.forEach(i2 => {
            numberList.push({
              userName: i2.userName,
              userId: i2.userId,
              userType: i2.userType,
              photoPath: i2.photoPath
            })
          })
        } else {
          numberList.push({
            userName: i.userName,
            userId: i.userId,
            userType: i.userType,
            photoPath: i.photoPath
          })
        }
      })
    }
    let data = {
      userId: userInfo.userId,
      userType: userInfo.userType,
      userName: userInfo.userName,
      eduId: userInfo.eduId,
      // scheduleDate: dayjs(startDate).format('YYYY-MM-DD'),
      // scheduleEndDate: dayjs(endDate).format('YYYY-MM-DD'),
      // startTime: startTime.length > 5 ? startTime.slice(0, 5) : startTime,
      // endTime: endTime.length > 5 ? endTime.slice(0, 5) : endTime,
      scheduleDate: dayjs(startTimeAll).format('YYYY-MM-DD'),
      scheduleEndDate: dayjs(endTimeAll).format('YYYY-MM-DD'),
      startTime: dayjs(startTimeAll).format('HH:mm'),
      endTime: dayjs(endTimeAll).format('HH:mm'),
      beAllDay: isAllDay,
      scheduleTitle: title,
      scheduleContent: description,
      scheduleLocation: address,
      remindFlag: remindFlag,
      remindTime: reminderTime,
      remindRealTime: remindRealTime,
      repeatTime: repeatTime,
      repeatTimeList: repeatTimeList,
      repeatEndTime: dayjs(repeatEndTime).format('YYYY-MM-DD'),
      beSkipHolidays: isRepeat ? isSkip ? 1 : 0 : 0,
      inviteCount: numberList.length,
      termStartDate: termStartDate,
      termEndDate: termEndDate,
      scheduleMemberBoList: numberList,
      beSignIn: beSign ? 1 : 0,
    }
    if (scheduleId) {
      data.scheduleId = scheduleId;
      data.originalScheduleDate = oldScheduleTime;
      data.scheduleMemberBoListOld = oldPeopleList;
      data.mainScheduleId = mainScheduleId;
    }
    if (repeatTime == 0) {
      delete data.repeatTimeList;
      delete data.repeatEndTime;
      delete data.beSkipHolidays;
    }

    HttpPost({
      url,
      data: data
    }).then((data) => {
      if (data.code == 200) {
        initData();
        setTimeout(() => {
          Taro.navigateBack({ delta: scheduleId ? 2 : 1 })
          // Taro.redirectTo({
          //   url: `/pages/scheduleApp/index?id=`
          // })
        }, 200);
        setTimeout(() => {
          Taro.showToast({
            title: (scheduleId ? '修改' : '添加') + '成功~',
            duration: 2000
          })
        }, 500);
      }
    })
  }


  const goBack = () => {
    initData();
    if (scheduleId) {
      Taro.navigateBack({
        delta: 1
      })
    } else {
      Taro.redirectTo({
        url: '/pages/scheduleApp/index'
      })
    }
  }

  const initWxSdk = async () => {
    const params = getWxSDKParams(['previewImage', 'getLocation'])
    wx.config(params);
    wx.ready(function () {
      // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
      console.log('ready')
    });
    wx.error(function (res) {
      // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
      console.log(res)
    });
  }

  useEffect(() => {
    document.title = (scheduleId ? '编辑' : '新建') + '日程'
    if (window.__wxjs_environment === 'miniprogram') {
      initWxSdk()
    }
    getCommonData()
    getRegularList()
    return () => {
      if (Utils.getSystemInfo() === 'weapp') {
        document.title = (scheduleId ? '编辑' : '新建') + '日程'
        window.getScheduleList && typeof window.getScheduleList === 'function' && window.getScheduleList()
      }
    }
  }, [scheduleId]);


  //点击常用日程标题
  const commonUse = (data) => {
    if (beExternal == 1) {
      Taro.showToast({
        title: '对外日程仅可修改提醒时间！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    setTitle(data.scheduleTitle)
  }

  //切换日程是否为全天 或 是否重复
  const stateSwitching = (type) => {
    if (type == 'allDay') {
      if (startDate && endDate && isAllDay == 0) {
        setIsAllDay(1);
        saveTime('00:00', 'start');
        saveTime('23:59', 'end');
      } else {
        setIsAllDay(0);
      }
    } else if (type == 'jump') {
      setIsSkip(!isSkip);
    } else {
      setIsRepeat(!isRepeat);
      if (isRepeat) {
        setRepeatTime(0);
      } else {
        setRepeatTime(1);
        setRepeatTimeList([]);
      }
    }
  }

  //存储开始/结束日期/结束重复日期
  const saveDate = (type, value,) => {
    if (type === "start") {
      setStartDate(value);
      setStartShow(false);
      setVisibleStart(true)
      handlePopLayer('close', 'start')
    } else if (type === "end") {
      setEndDate(value);
      setEndShow(false);
      setVisibleEnd(true)
      handlePopLayer('close', 'end')
    } else if (type === "repeatEnd") {
      setRepeatEndTime(dayjs(value).format('YYYY-MM-DD'));
      setRepeatEndShow(false);
      handlePopLayer('close', 'repeatEnd')
    }
  }

  // 存储开始/结束时间时分秒
  const saveTime = (value, type) => {
    let fullData = ''
    let date = ''
    // console.log(value, 'saveTime');

    if (type == 'start') {
      fullData = dayjs(startDate).format('YYYY-MM-DD');
      date = `${fullData} ${value}`;
      // let startTimeAll = constructionDate2(date);
      let startTimeAll = dayjs(date).format('YYYY-MM-DD HH:mm');

      setStartTime(value);
      setStartTimeAll(dayjs(startTimeAll).format('YYYY-MM-DD HH:mm'));
      setVisibleStart(false);
    } else {
      fullData = dayjs(endDate).format('YYYY-MM-DD');
      date = `${fullData} ${value}`;
      // let endTimeAll = constructionDate2(date);
      let endTimeAll = dayjs(date).format('YYYY-MM-DD HH:mm');

      setEndTime(value)
      setEndTimeAll(dayjs(endTimeAll).format('YYYY-MM-DD HH:mm'))
      setVisibleEnd(false)
    }
  }

  //选择提醒频率日期
  const selectRepeatData = (id) => {
    let dateList = repeatTimeList.concat([]);
    if (dateList.indexOf(id) >= 0) {
      dateList = dateList.filter(item => item != id);
      setIsCheck(0);

    } else {
      dateList.push(id);
      setIsCheck(1);
    }
    // console.log(dateList, 'dateList', id);

    setRepeatTimeList(dateList);
    setIsSelect(!isSelect);
    // setIsSelect(false);
  }

  //跳转参与人选择页面
  const goSelectUser = () => {
    if (beExternal == 1) {
      Taro.showToast({
        title: '对外日程仅可修改提醒时间！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    Taro.navigateTo({
      // url: '/pages/scheduleApp/selectUser/index'
      url: '/pages/scheduleApp/selectUserNew/index'//2023-07-18更换新的移动端用户选择组件
    })
  }

  // 操作常用设置
  const operation = (type, item) => {
    switch (type) {
      case 'source': console.log(type, 'type');
        break;
      case 'set': setOldValue(item.scheduleTitle), setInputPopOpen(true), setOldItem(item);
        break;
      case 'add': setOldValue(''), setOldItem(''), setInputPopOpenNew(true);
        break;
      case 'edit':
        let url = '/pages/scheduleApp/createSchedule/index?id=' + scheduleId
        Taro.navigateTo({
          url
        });
        break;
      case 'del':
        Taro.showModal({
          title: '提示',
          content: '是否删除该常用日程？',
          success: function (res) {
            if (res.confirm) {
              HttpDelete({
                url: '/api/schedule/regular/delete?id=' + (item.beInit == 0 ? item?.id : item.initId) + '&beInit=' + item.beInit
                  + '&userId=' + userInfo.userId + '&eduId=' + userInfo.eduId,
                // data: {
                //   id: item.beInit == 0 ? item?.id : item.initId,
                //   beInit: item.beInit,
                //   userId: userInfo.userId,
                //   schoolId: userInfo.schoolId,
                // }
              }).then((result) => {
                if (result.code === '200') {
                  getRegularList();
                  Taro.showToast({
                    title: '删除成功',
                    duration: 2000,
                    mask: true
                  })
                }
              })
            } else if (res.cancel) {
              // console.log('用户点击取消')
            }
          }
        })
        break;
    }

  }

  const inputPop_confirm = (value) => {
    console.log(value, 'value', oldItem);

    if (!value) {
      console.log("输入值不能为空");
      Taro.showToast({ title: "常用日程名称不能为空", icon: 'none', duration: 1000 })
      return
    }
    // if (!oldItem) return;
    if (value == oldItem.scheduleTitle) {
      Taro.showToast({ title: "请输入新的常用日程名称", icon: 'none', duration: 1000 })
      return
    }
    let url = '/api/schedule/regular/save'
    let data = {
      userId: userInfo.userId,
      userType: userInfo.userType,
      eduId: userInfo.eduId,
      id: oldItem?.id,
      scheduleTitle: value,
      beHide: oldItem ? oldItem.beHide : 0,
      initId: oldItem ? oldItem.initId : '',
      beInit: oldItem ? oldItem.beInit : 0,
      beCanDelete: oldItem ? oldItem.beCanDelete : 1,
      sort: oldItem.sort,
    }
    HttpPost({
      url,
      data: data
    }).then((data) => {
      if (data.code == 200) {
        getRegularList();
        Taro.showToast({
          title: '设置成功',
          duration: 2000,
          mask: true
        })
      } else {
        Taro.showToast({
          title: data.msg,
          icon: 'none',
          duration: 2000
        })
      }
      setInputPopOpen(false);
      setInputPopOpenNew(false);
    })
  }

  const inputPop_cancel = () => {
    setInputPopOpen(false);
    setInputPopOpenNew(false);
    setOldValue('');
  }

  return (
    <View className="scheduleTitle">
      {
        Utils.getQueryVariable('env') === 'weapp' || window.__wxjs_environment === 'miniprogram' ?
          "" :
          <Header
            className='header-top'
            mainTitle={`${scheduleId ? '编辑' : '新建'}日程`}
            mainTitleBold={false}
            isTitlePositionLeft={true}
            needMainIcon={process.env.TARO_ENV === 'weapp' ? false : true}
            onClick={Taro.getCurrentInstance().router?.params.from ? goBack : ''}
          />
      }

      <View className="create-schedule">
        <View className='create-schedule-top'>
          <LgInput
            value={title}
            maxLength={30}
            type="A"
            isNeed={true}
            inputName={'日程标题'}
            placeholder="输入日程标题"
            onChange={value => setTitle(value)}
            isReadonly={beExternal == 1 ? true : false}
          ></LgInput>
          {
            regularList.length > 0 ?
              <><View className="line"></View>
                <View className='commonly-used'>
                  <Text className='commonly-used-left'>常用:</Text>
                  <View className='commonly-used-right'>
                    {regularList.map(item => {
                      if (item.beHide == '1')
                        return
                      return (
                        <Text className='commonly-used-item' onClick={() => commonUse(item)}>{item?.scheduleTitle}</Text>
                      )
                    })}
                    <i className='commonly-setting' onClick={() => { document.body.style.overflow = 'hidden'; setCommonlyVisible(true) }}></i>
                  </View>
                </View></> : ''}
          {/* 输入框弹窗 */}
          <PrPopInput
            oldValue={oldValue}
            title='重命名'
            isOpen={inputPopOpen}
            confirm={inputPop_confirm}
            cancel={inputPop_cancel}
            placeholder='请输入常用日程标题…'
          ></PrPopInput>
          <PrPopInput
            title='创建常用日程'
            isOpen={inputPopOpenNew}
            confirm={inputPop_confirm}
            cancel={inputPop_cancel}
            placeholder='请输入常用日程标题…'
          ></PrPopInput>
          <LgPopLayer
            position="bottom"
            confirm={() => { handlePopLayer('close', 'commonly') }}
            showLayer={() => handlePopLayer('close', 'commonly')}
            title={'常用日程设置(最多添加12条)'}
            showClose
            isOpen={commonlyVisible}>
            {
              regularList.length < 12 ?
                <View>
                  <View className='commonly-add' onClick={() => operation('add', '')}>添加</View>
                  <View className='commonly-add-shu'>|</View>
                </View>
                : ''
            }
            {
              regularList.map((item, index) => {
                return (
                  <View className="kind-one" key={index} onClick={() => changeScheduleTime(item)}>
                    <LgSlide data={item?.optionList} canSlide={true} key={commonlyVisible + (item?.id || item?.initId)}>
                      <View style={{ width: '100vw' }}>
                        <View className={item.beInit == '1' ? 'kind-init' : 'kind-title'}>
                          {item?.scheduleTitle}
                        </View>
                      </View>
                      {/* <View className='commonly-setting'>
                          {
                            item.beInit == '1' ? '' :
                              <i className='set-name' onClick={() => operation('set', item)}></i>
                          }
                          <View className='del-commonly' onClick={() => { operation('del', item) }}>X</View>
                        </View> */}
                    </LgSlide>
                  </View>
                )
              })
            }
          </LgPopLayer>
          <View className="line"></View>
          {/* <View className='schedule-type'>
          </View> */}
          {/* <View className="line"></View> */}
          <LgCell
            title="开始时间"
            content={
              startTimeAll ? startTimeAll : '请选择'
            }
            showIcon={true}
            onClick={() => {
              if (isAllDay == 0) {
                handlePopLayer('open', 'start');
              } else {
                Taro.showToast({
                  title: '当前已选择全天，不可操作时间',
                  duration: 2000,
                  icon: 'none'
                })
              }
            }}
            type='A'
          ></LgCell>
          <DatePicker
            title="开始时间选择"
            startDate={startDate1}
            endDate={endDate1}
            defaultValue={new Date(startTimeAll)}
            visible={startShow}
            type="datetime"
            onClose={() => setStartShow(false)}
            onConfirm={(options, values,) => saveTimeNew(values, options, 'start')}
            key={String(startShow + '1')}
          />
          {/* <LgCalendar type="A" props={{
            selectedDay: constructionDate2("", 3),
            isOpen: startShow,
            confirm: (date) => saveDate('start', date),
            onClose: () => handlePopLayer('close', 'start',)
          }} />
          <LgTimeSelect type='B' timeProps={{
            isOpen: visibleStart,
            name: '创建时间',
            value: currentTime,
            onChange: (value) => saveTime(value, 'start'),
            onClose: () => handlePopLayer('close', 'full')
          }} /> */}

          <View className="line"></View>
          <LgCell
            title="结束时间"
            content={
              endTimeAll ? endTimeAll : '请选择'
            }
            showIcon={true}
            onClick={() => {
              if (isAllDay == 0) {
                handlePopLayer('open', 'end');
              } else {
                Taro.showToast({
                  title: '当前已选择全天，不可操作时间',
                  duration: 2000,
                  icon: 'none'
                })
              }
            }}
            type='A'
          ></LgCell>
          <DatePicker
            title="结束时间选择"
            startDate={startDate1}
            endDate={endDate1}
            defaultValue={new Date(endTimeAll)}
            visible={endShow}
            type="datetime"
            onClose={() => setEndShow(false)}
            onConfirm={(options, values,) => saveTimeNew(values, options, 'end')}
            key={String(startShow)}
          />
          {/* <LgCalendar type="A" props={{
            selectedDay: constructionDate2("", 3),
            isOpen: endShow,
            confirm: (date) => saveDate('end', date),
            onClose: () => handlePopLayer('close', 'end',)
          }} />
          <LgTimeSelect type='B' timeProps={{
            isOpen: visibleEnd,
            name: '创建时间',
            value: currentTimeEnd,
            onChange: (value) => saveTime(value, 'end'),
            onClose: () => handlePopLayer('close', 'full')
          }} /> */}
          <View className="line"></View>
          {
            init ?
              <View className='all-day'>
                <Text className='all-day-left'>全天</Text>
                <View className='all-day-right'><LgSwitch onClick={() => stateSwitching('allDay')} default={isAllDay} disabled={(startTimeAll && endTimeAll) && beExternal == 0 ? false : true} /></View>
              </View> : ''
          }
        </View>
        <View className='advanced-settings'>
          <Text className='advanced-settings-text'>高级设置</Text>
        </View>
        <View className="create-schedule-bottom">
          <View className='address'>
            <LgInput
              value={address}
              maxLength={20}
              type="A"
              inputName={'地点'}
              placeholder="输入日程地点"
              onChange={value => setAddress(value)}
              isReadonly={beExternal == 1 ? true : false}
            ></LgInput>
          </View>
          {
            userInfo.userType !== '2' ?
              <><View className="line"></View><LgCell
                title="参与人"
                content={arr33 && arr33.length > 0 ?
                  <View className='participant'>{arr33.map((item, index) => {
                    if (item.hasOwnProperty('structureVoList')) {
                      console.log(item)
                      return <>
                        {
                          item.structureVoList.map(i => {
                            console.log(i)
                            return (
                              i.userName + (item.structureVoList.length > 1 && index < item.structureVoList.length - 1 ? '，' : '')
                            )
                          })
                        }
                      </>
                    } else {
                      return (
                        item.userName + (arr33.length > 1 && index < arr33.length - 1 ? '，' : '')
                      )
                    }
                  })}</View> : <Text style={{ color: '#cccccc' }}>请选择</Text>}
                showIcon={true}
                onClick={() => {
                  goSelectUser()
                }}
                type='A'
              ></LgCell></> : ''
          }
          <View className="line"></View>
          {
            init ?
              <View className='be_SignIn'>
                <Text className='be_SignIn_btn'>会议签到</Text>
                <View className='be_SignIn_right'><LgSwitch onClick={() => setBeSign(!beSign)} default={beSign} /></View>
              </View> : ''
          }
          {/* <LgSelectModal
            token={getToken()}
            officeUrl={baseUrl}
            selectUserList={selectUserList}
            recentList={recentList}
            onConfirm={(data) => { console.log(data) }}
          ></LgSelectModal> */}
          {/* <LgSeleTarget 
            type="A"
            onConfirm
            dataList
            showNameAttr
            subListAttr
            confirmBtnName
            choNumUnit
            getNumber
            getSubList
            setVal
            getVal
          >
          </LgSeleTarget> */}
          <View className="line"></View>

          <LgInput
            value={description}
            type="B"
            inputName="日程描述"
            placeholder="请输入日程内容..."
            maxLength={200}
            onChange={value => {
              setDescription(String(value)); console.log(value, 'value');
            }}
            isReadonly={beExternal == 1 ? true : false}
          ></LgInput>
          <View className="line"></View>

          <LgCell
            title="日程提醒"
            content={
              reminderName && isAllDay == 0 ? reminderName : isAllDay == 1 ? '默认提醒时间为00:00' : '不提醒'
            }
            showIcon={true}
            onClick={() => {
              if (isAllDay == 0) {
                handlePopLayer('open', 'reminder');
              } else {
                Taro.showToast({
                  title: '全天状态下默认提醒时间为00:00，不可修改！',
                  icon: 'none',
                  duration: 2000
                })
              }
            }}
            type='A'
          ></LgCell>
          <LgPopLayer
            position="bottom"
            confirm={() => { handlePopLayer('close', 'reminder') }}
            showLayer={() => handlePopLayer('close', 'reminder')}
            title={'提醒时间'}
            showClose
            isOpen={visible}>
            {
              reminderList.map((item, index) => {
                return (
                  <View className="kind-one" key={index} onClick={() => changeScheduleTime(item)}>{item.reminderName}</View>
                )
              })
            }
          </LgPopLayer>
          <View className="line"></View>
          {
            init ?
              <View className='schedule-repeat'>
                <Text className='schedule-repeat-left'>重复</Text>
                <View className='schedule-repeat-right'><LgSwitch onClick={() => stateSwitching('repeat')} default={isRepeat} disabled={beExternal == 0 ? false : true} /></View>
              </View>
              : ''
          }
          {
            init && isRepeat ?
              <><View className="line"></View><View className='schedule-repeat'>
                <Text className='schedule-repeat-left'>自动跳过节假日<Text style={{ color: '#999', fontSize: '14px' }}>(节假日来源于校历)</Text></Text>
                <View className='schedule-repeat-right'><LgSwitch onClick={() => stateSwitching('jump')} default={isSkip} disabled={beExternal == 0 ? false : true} /></View>
              </View></>
              : ''
          }
          {
            isRepeat ?
              <View className="line"></View>
              : ''
          }
          {
            isRepeat == true ?
              <><LgCell
                title="结束重复时间"
                content={
                  repeatEndTime ? repeatEndTime : '请选择'
                }
                showIcon={true}
                onClick={() => {
                  handlePopLayer('open', 'repeatEnd');
                }}
                type='A'
              ></LgCell>
                <DatePicker
                  title="结束重复日期"
                  visible={repeatEndShow}
                  pickerProps={{
                    popupProps: { zIndex: 1220 },
                  }}
                  defaultValue={new Date(`${endTimeAll}`)}
                  showChinese
                  onCancel={() => setRepeatEndShow(false)}
                  onConfirm={(options, values) => {
                    setRepeatEndShow(false)
                    saveTimeNew(values, options, '')
                  }}
                />
                {/* <LgCalendar type="A" props={{
                  selectedDay: constructionDate2("", 3),
                  isOpen: repeatEndShow,
                  confirm: (date) => saveDate('repeatEnd', date),
                  onClose: () => handlePopLayer('close', 'repeatEnd',)
                }} /> */}
                <View className="line"></View>
                <LgCell
                  title="频率"
                  content={
                    repeatTimeType[repeatTime]
                  }
                  showIcon={true}
                  onClick={() => {
                    handlePopLayer('open', 'frequency')
                  }}
                  type='A'
                ></LgCell>
                <LgPopLayer
                  position="bottom"
                  confirm={() => handlePopLayer('close', 'frequency')}
                  showLayer={() => handlePopLayer('close', 'frequency')}
                  title={'提醒频率'}
                  showClose
                  isOpen={frequencyShow}>
                  {
                    repeatTimeTypeList.map((item, index) => {
                      return (
                        // <View className="kind-one" key={index} >{item.repeatName}</View>
                        <View className="kind-one" key={index} onClick={() => { setRepeatTime(index + 1), handlePopLayer('close', 'frequency') }}>{item.repeatName}</View>
                      )
                    })
                  }
                </LgPopLayer>
                {
                  repeatTime == 2 || repeatTime == 3 ?
                    <View className='repeat-date'>
                      {repeatTime == 2 ?
                        week.map((item, index) => {
                          return (
                            <View key={index} className={repeatTimeList.indexOf(item.id) >= 0 ? 'repeat-date-one active' : 'repeat-date-one'} onClick={() => selectRepeatData(item.id)}>
                              <Text className='repeat-date-num'>{item.weekName}</Text>
                              {
                                repeatTimeList.map((itm, idx) => {
                                  if (itm == item.id) {
                                    return (
                                      <View className='repeat-date-check'>
                                        <LgCheckbox key={index} type='B' default={1} value={1} ></LgCheckbox>
                                      </View>
                                    )
                                  }
                                })
                              }

                            </View>
                          )
                        })
                        :
                        month.map((item, index) => {
                          return (
                            <View key={index} className={repeatTimeList.indexOf(item.id) >= 0 ? 'repeat-date-one active' : 'repeat-date-one'} onClick={() => selectRepeatData(item.id)}>
                              <Text className='repeat-date-num'>{item.id}</Text>
                              {
                                repeatTimeList.map((itm, idx) => {
                                  if (itm == item.id) {
                                    return (
                                      <View className='repeat-date-check'>
                                        <LgCheckbox type='B' default={1} value={1} ></LgCheckbox>
                                      </View>
                                    )
                                  }
                                })
                              }
                            </View>
                          )
                        })

                      }
                      {repeatTimeList.indexOf(31) >= 0 ? <Text className='tips'>没有31日的月份则需选择30日进行重复</Text> : ''}
                    </View>
                    : ''
                }
              </>
              : ''
          }

        </View>


      </View>

      <View className="index-footer">
        <LgButton className="send-btn cancel-btn" type='D' onClick={() => goBack()}> 取消</LgButton>
        <LgButton className="send-btn confirm-btn" type='B' onClick={() => createSchedule()} >确定</LgButton>
      </View>
    </View>
  )
}

const mainProps = ({ commonData }) => {
  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    noticeAddr: commonData.noticeAddr,
    baseUrl: commonData.baseUrl,
    selectUserList: commonData.selectUserList,//参会人
  }
}

export default connect(mainProps)(App);
